#@revision $Revision$ 
#@author Jorge Niedbalski R. <jnr@niedbalski.org>

from urlparse import urlparse
from Config      import Config

import httplib
import urllib

class    Observer:
    def   notify(self, data):
        pass    
        
    def   notifyResponse(self):                
        pass

class    ObserverSubject:

    def   _init_(self):
        self._observerCollection = []
    
    def   registerObserver(self, observer):
        if self._observerCollection._contains_(observer):
            raise Exception("Observer %s alread exists" % ( observer)
        self._observerCollection.append(observer)
        return True 

    def   notifyObservers(self, task_unique_id, data, running_time):
        for observer in self._observerCollection:
            observer.notify(task_unique_id, data, running_time)

class    SCQueueObserver(Observer):

    def   _init_(self, url):
        self._url = urlparse(url)

    def   notify(self, task_unique_id, data, running_time):
        params  = urllib.urlencode({'task_id' : task_unique_id, 'data' : data, 'running_time' : running_time })
        headers = { 
                    "Content-type" : "application/x-www-form-urlencoded",
                    "Accept"        : "text/plain" 
                  }            
        conn     = httplib.HTTPConnection(self._url.netloc)
        conn.request("POST", self._url.path, params, headers)
        response = conn.getresponse()        

        self.notifyResponse(task_unique_id, response.status)
        conn.close()

        return True                          
        
    def   notifyResponse(self, task_unique_id, status):
        if Config.DEBUG:
            print "Notification response %s for task id %s" % ( status, task_unique_id 
                
